package demo2;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-04-02
 * Time: 11:00
 */
public class SeqList{
    private int[] elem;
    private int  size;
    private static final int default_capacity = 5;
    public SeqList() {
        this.elem = new int[default_capacity];
    }
    public void display() {
        for (int i = 0; i < this.size; i++) {
            System.out.println(this.elem[i] + " ");
        }
        System.out.println();
    }
    public void add(int data) {
        //判断是否满
        if(isFull()){
            resize();
        }
        this.elem[this.size] = data;
        this.size++;
    }
    public boolean isFull() {
        return size == elem.length;
    }
    public boolean contains(int toFind) {
        if(indexOf(toFind) != -1) {
            return true;
        }
        return false;
    }
    public int indexOf(int toFind) {
        for (int i = 0; i < this.size; i++) {
            if(this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }
    public int get(int pos) {
        if( !checkPos(pos)) {
            throw new PosOutException("get pos error");
        }
        return this.elem[pos];
    }
    public int getSize() {
        return this.size;
    }
    public void set(int pos, int value) {
        if( !checkPos(pos)) {
            throw new PosOutException("set pos error");
        }
        this.elem[pos] = value;

    }
    private boolean checkPos(int pos) {
        return pos >= 0 && pos < this.size;
    }
    public void add(int pos, int data) {
        if(isFull()){
            resize();
        }
        if(pos < 0 || pos > this.size) {
            throw new PosOutException("add pos error");
        }
        for (int i = size - 1; i >= pos; i--) {
            this.elem[i + 1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.size++;
    }
    private void resize() {
        this.elem = Arrays.copyOf(elem,2*elem.length);
    }
    public void delete(int data) {
        int pos = indexOf(data);
        if(pos == -1) {
            throw new PosOutException("数据不存在");
        }
        for(int i = pos; i < this.size - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.size--;
    }
    public void clear() {
//        for (int i = 0; i < this.size; i++) {
//            this.elem[i] = null;
//        }
        this.size = 0;
    }
}

